package com.xuecheng.media.controller;

import com.xuecheng.commons.model.dto.MediaDto;
import com.xuecheng.commons.model.dto.MediaQueryDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.VodUploadDto;
import com.xuecheng.commons.model.vo.MediaVo;
import com.xuecheng.commons.model.vo.ResourceVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.VodUploadVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.service.MediaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 媒资信息前端控制器
 * </p>
 *
 * @author itheima
 */
@Slf4j
@RestController
@RequestMapping("/media")
public class MediaController {

    @Autowired
    private MediaService  mediaService;

    /**
     * 获取上传凭证
     * POST /vod-token
     * 参数：VodUploadDto
     * 响应：ResponseResult<VodUploadVo>
     */
    @PostMapping("/vod-token")
    public ResponseResult<VodUploadVo> createToken(@RequestBody VodUploadDto dto) throws Exception {
        return mediaService.createToken(dto);
    }

    /**
     * 刷新上传凭证
     *  GET /refresh-vod-token/{videoId}
     *  参数：videoId（阿里云生成的）
     *  响应：ResponseResult<VodUploadVo>
     */
    @GetMapping("/refresh-vod-token/{videoId}")
    public ResponseResult<VodUploadVo> refreshToken(@PathVariable("videoId") String videoId)  throws Exception  {
        return mediaService.refreshToken(videoId);
    }

    /**
     * 保存媒资信息到数据库中
     * Path：POST
     * 参数：MediaDto
     * 响应：ResponseResult
     */
    @PostMapping
    public ResponseResult saveMedia(@RequestBody MediaDto dto)  throws Exception  {
        return mediaService.saveMedia(dto);
    }

    /**
     * 分页查询媒资列表
     * POST /list
     * 参数：
     *    Query：PageRequest
     *    Body：MediaQueryDto
     * 响应
     *   PageResponseResult<MediaVo>
     */
    @PostMapping("/list")
    public ResponseResult<MediaVo> list(PageRequest request, @RequestBody MediaQueryDto dto) {
        return mediaService.findAll(request,dto);
    }

    /**
     * 根据id查询媒资
     */
    @GetMapping("/{mediaId}")
    public ResponseResult<MediaVo> findById(@PathVariable("mediaId") Long mediaId) {
        //根据id，调用service查询：Media
        Media media = mediaService.getById(mediaId);
        //转化成vo
        MediaVo vo = BeanHelper.copyProperties(media, MediaVo.class);
        return ResponseResult.okResult(vo);
    }

    /**
     * 根据id，查询媒资的播放地址
     *    GET /media-url/{mediaId}
     *    ResponseResult<ResourceVo>
     */
    @GetMapping("/media-url/{mediaId}")
    public ResponseResult<ResourceVo> findMediaUrl(@PathVariable("mediaId") Long mediaId) throws Exception {
        return mediaService.findMediaUrl(mediaId);
    }
}
